package com.example.shop_2210.detail

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.AddCarEntityResult
import com.example.base.entity.DetailEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class DetailViewModel:BaseViewModel() {
    //展示详情
    val detailSuccess = MutableLiveData<DetailEntityResult>()
    val detailFail = MutableLiveData<String>()
    fun detail(id:Int,type:String){
        viewModelScope.launch {
            try {
                detailSuccess.value = apiService.detail(id,type)
            }catch (e:Exception){
                detailFail.value = e.message
            }
        }
    }
    //添加购物车
    val addSuccess = MutableLiveData<AddCarEntityResult>()
    val addFail = MutableLiveData<String>()
    fun add(cartNum:Int,productAttrUnique:String,productId:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map.put("cartNum",cartNum)
                map.put("productAttrUnique",productAttrUnique)
                map.put("productId",productId)
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                addSuccess.value = apiService.addCar(body)
            }catch (e:Exception){
                addFail.value = e.message
            }
        }
    }

}